﻿using System;
using MessageSystem.Managed.Interface;
using MessageSystem.Managed.Infrastructure;
using MessageSystem.Managed;

namespace MessageSystem.Managed.Rpc
{
    public class RpcCenter
    {
        IMessageSystem _messagesystem;

        public RpcCenter(Options op,MessageSystemType nType)
        {
            _messagesystem = MessageSystemFactory.Create(nType);
            _messagesystem.Create(op);
        }

        public void CreateDomain(RpcAddress address,Action<RpcDomain> returnCall)
        {
            _messagesystem.ListenLocalSystem(address.Ip, address.Port, delegate(IMessageChannel mc)
            {
                RpcDomain domain = new RpcDomain(mc,address);
                returnCall(domain);
            });
        }

        public void GetDomain(RpcAddress address, Action<RpcDomain> returnCall)
        {
            _messagesystem.ConnectRemoteSystem(address.Ip, address.Port, delegate(IMessageChannel mc)
            {
                RpcDomain domain = new RpcDomain(mc,address);
                returnCall(domain);
            },
            delegate()
            {
                returnCall(null);
            });
        }

        public RpcPermanentDomain GetPermanentDomain(RpcAddress address,int tryTimes,int delaySeconds)
        {
            RpcPermanentDomain domain = new RpcPermanentDomain(address, _messagesystem, tryTimes, delaySeconds);
            return domain;
        }

        public void Poll(int waittime=20)
        {
            _messagesystem.Poll(waittime);
        }
    }
}
